<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 
      相当于一个简单的盒子
    -->

    <el-card class="box-card">
      <div>
        <!-- 绘制搜索区域 -->
        <el-row :gutter="20">
          <el-col :span="9">
            <div>
              <!-- 点击清楚按钮自动触发事件然后调用重新获取函数 -->
              <el-input
                placeholder="请输入内容"
                v-model="queryInfo.query"
                clearable
                v-on:clear="this.getUserList"
              >
                <el-button slot="append" icon="el-icon-search" v-on:click="search_button()"></el-button>
              </el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
            <!-- 点击添加用户需要触发一个盒子模态框 -->
          </el-col>
        </el-row>
        <!-- 模态框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          width="50%"
          v-on:close="addDiagClosed"
        >
          <!-- 编辑新增用户需要的信息  需要新增表单 -->

          <el-form v-bind:model="addForm" :rules="addFormRules" ref="addFormRef">
            <!-- //用户名 -->
            <el-form-item prop="username" label="用户名">
              <!-- prop 绑定验证规则 -->
              <el-input v-model="addForm.username" type="text"></el-input>
            </el-form-item>
            <!-- 密码 -->
            <!-- prop 绑定验证规则 -->
            <el-form-item prop="password" label="密码">
              <el-input v-model="addForm.password" type="password"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input v-model="addForm.email" type="text"></el-input>
            </el-form-item>
            <el-form-item prop="mobile" label="手机号">
              <el-input v-model="addForm.mobile" type="text"></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false" v-on:click="addFormData">确 定</el-button>
          </span>
        </el-dialog>

        <el-table :data="users" border stripe>
          <el-table-column label="#" type="index" align="center"></el-table-column>
          <el-table-column label="姓名" prop="username" align="center"></el-table-column>
          <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
          <el-table-column label="电话" prop="mobile" align="center"></el-table-column>
          <el-table-column label="角色" prop="role_name" align="center"></el-table-column>
          <el-table-column label="状态" prop="mg_state" align="center">
            <template slot-scope="scope">
              <!-- {{scope.row}} -->
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                v-on:change="handle(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop align="center">
            <template slot-scope="scope">
              <!-- 修改按钮  点击修改的时候需要通过插槽的scope.row将数据传递给点击事件 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUserData(scope.row)"
              ></el-button>
              <!-- 删除按钮  点击删除的时候也一样需要将信息传递给执行函数-->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delUser(scope.row)"
              ></el-button>
              <!-- 分配角色按钮 -->

              <el-tooltip
                class="item"
                effect="dark"
                content="角色分配"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="settingUser(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total1"
        ></el-pagination>
      </div>

      <!-- 点击修改按钮弹出模态框 -->
      <el-dialog
        title="编辑用户信息"
        :visible.sync="editdialogVisible"
        width="50%"
        @close="editDiagClosed"
      >
        <el-form v-bind:model="editForm" :rules="editFormRules" ref="editFormRef">
          <!-- //用户名 -->
          <el-form-item prop="username" label="用户名">
            <!-- prop 绑定验证规则 用户名禁止修改 -->
            <el-input v-model="editForm.username" type="text" disabled></el-input>
          </el-form-item>
          <!-- 密码 -->
          <!-- prop 绑定验证规则 -->
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="editForm.email" type="text"></el-input>
          </el-form-item>
          <el-form-item prop="mobile" label="手机号">
            <el-input v-model="editForm.mobile" type="text"></el-input>
          </el-form-item>
        </el-form>

        <!-- editdialogVisible = false -->

        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSave">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 点击设置弹出模态框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="settingdialogVisible"
        width="50%"
        @close="settingDiagClosed"
      >
        <p>当前的用户:{{userinfo.username}}</p>
        <p>当前的角色:{{userinfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleslist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="settingdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="settingSave">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    //校验添加用户和修改用户的邮箱及手机号的信息
    var checkemail = (rule, value, callback) => {
      var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (reg.test(value)) {
        return callback()
      }
      return callback(new Error('邮箱填写错误'))
    }

    var checkmobile = (rule, value, callback) => {
      var reg1 = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/
      if (reg1.test(value)) {
        return callback()
      }
      return callback(new Error('请填写正确手机号'))
    }

    return {
      // 获取用户列表的对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      users: [],
      total1: 1,
      // 添加用户的信息
      dialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        // 验证用户名是否合法 trigger验证的时间 是在焦点离开后 require 表示需要验证
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }],
        email: [{ validator: checkemail, trigger: 'blur' }],
        mobile: [{ validator: checkmobile, trigger: 'blur' }]
      },

      //修改用户的信息
      editdialogVisible: false,
      id: '',
      editForm: {
        username: '',
        email: '',
        mobile: '',
        mg_state: ''
      },
      editFormRules: {
        // 验证用户名是否合法 trigger验证的时间 是在焦点离开后 require 表示需要验证
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }],
        email: [{ validator: checkemail, trigger: 'blur' }],
        mobile: [{ validator: checkmobile, trigger: 'blur' }]
      },
      settingdialogVisible: false,
      userinfo: {},
      roleslist: [],
      selectedRoleId:''
    }
  },
  methods: {
    async search_button() {
      // console.log(this.queryInfo.query);
      // 获取用户输入的姓名然后在发起axios提交请求
      let { data: res } = await this.axios.get('users', { params: this.queryInfo })
      // console.log(res); //获取结果后然后渲染结果
      this.users = res.data.users
    },
    async getUserList() {
      let { data: res } = await this.axios.get('users', { params: this.queryInfo })
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      if (res.meta.status == 200) {
        this.total1 = res.data.total
        this.users = res.data.users
      }
    },
    // 监听每页的条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    //监听当前页码
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 点击权限开关，出发handl动作去开启和关闭用户权限
    async handle(val) {
      // console.log(val);
      // 接下来发起请求  users/:uId/state/:type
      let { data: res } = await this.axios.put(`users/${val.id}/state/${val.mg_state}`)

      console.log(res)
      if (res.meta.status != 200) {
        //需要将前端按钮还原
        users.mg_state = !users.mg_state
        return this.$message.error('操作异常')
      }
      if (res.meta.status == 200) {
        return this.$message.success('操作成功')
      }
    },
    // 关闭表单则清空输入的数据
    addDiagClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 执行添加表单元素
    addFormData() {
      // 1.进行预校验
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) {
          return this.$message.error('请将信息填写正确')
        }
        // 如果填写没问题则开始发起请求进行预校验
        let { data: res } = await this.axios.post('users', {
          username: this.addForm.username,
          password: this.addForm.password,
          email: this.addForm.email,
          mobile: this.addForm.mobile
        })
        console.log(res)
        if (res.meta.status != 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        // 添加成功后调用函数重新加载页面
        this.getUserList()
      })
    },

    //修改用户信息数据
    // 关闭表单则清空输入的数据
    editDiagClosed() {
      this.$refs.editFormRef.resetFields()
    },

    editUserData(val) {
      this.editdialogVisible = true
      console.log(val) // 用户的id就是val.id
      this.id = val.id
      // 将获取到的用户的val信息填充到对应的editForm
      this.editForm = val
    },
    // 当用户修改数据后点击保存需要修改数据
    editSave() {
      // 点击保存后1.获取数据 this.$refs.editFormRef可以获取所有的数据
      // 2.发起axios请求去保存数据 保存前需要先对数据进行校验
      this.$refs.editFormRef.validate(async valid => {
        console.log(this.$refs.editForm)
        if (!valid) {
          return this.$message.error('请将信息填写正确')
        }
        //console.log(this.editForm.mg_state,this.editForm.username,this.editForm.email,this.editForm.mobile,this.id);
        // ：users/:uId/state/:type
        let { data: res } = await this.axios.put(`users/${this.id}/`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        console.log(res)
        if (res.meta.status != 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.getUserList()
        //成功后关闭模态弹窗
        this.editdialogVisible = false
      })
    },
    // 删除用户
    delUser(val) {
      console.log(val.id)

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async vals => {
          if (vals == 'confirm') {
            //val===='confirm'则说明是真的 则发请求删除用户数据
            let { data: res } = await this.axios.delete('users/' + val.id)
            if (res.meta.status !== 200) return this.$message.error('删除失败')
            this.$message.success('删除成功')
            //重新加载列表
            this.getUserList()
          }
        })
        .catch(err => {
          // console.log(err);

          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 设置用户信息
    async settingUser(userinfo) {
      this.settingdialogVisible = true
      this.userinfo = userinfo
      // console.log(userinfo);

      //  获取所有的角色列表
      let { data: res } = await this.axios.get('roles/')
      if (res.meta.status !== 200) return this.$message.error('获取角色信息错误')
      //成功后将所有的列表保存到数据中
      this.roleslist = res.data
    },
    settingDiagClosed() {
      // 设置窗口关闭重置相关对象
      this.selectedRoleId='',
      this.userinfo={}
    },
    async settingSave() {
      // 点击保存将数据提交到对应的接口  users/:id/role users/:id/role
      if(!this.selectedRoleId) return this.$message.error('请选择对应的角色');
      let {data:res}=await this.axios.put(`users/${this.userinfo.id}/role`,{
        rid:this.selectedRoleId
      })
      if(res.meta.status!==200) return this.$message.error('设置失败')
      this.$message.success('设置成功')
      this.getUserList();
      this.settingdialogVisible=false
    }
  },
  created() {
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
.box-card {
  margin-top: 15px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
  text-align: center;
}
</style>
